// @ts-ignore
import axios, {AxiosRequestConfig} from 'axios'

class HttpUtils {

    constructor() {
        // 自定义适配器来适配uniapp语法
        axios.defaults.adapter = function(config: any) {
            return new Promise((resolve, reject) => {
                let settle = require('axios/lib/core/settle');
                let buildURL = require('axios/lib/helpers/buildURL');
                uni.request({
                    method: config.method.toUpperCase(),
                    url: (config.baseURL ? config.baseURL : "") + buildURL(config.url, config.params, config.paramsSerializer),
                    header: config.headers,
                    data: config.data,
                    dataType: config.dataType,
                    responseType: config.responseType,
                    sslVerify: config.sslVerify,
                    complete: function complete(response: any) {
                        response = {
                            data: response.data,
                            status: response.statusCode,
                            errMsg: response.errMsg,
                            header: response.header,
                            config: config
                        };
                        settle(resolve, reject, response);
                    }
                })
            })
        }
    }

    async get(url: string, config?: AxiosRequestConfig) {
        let data = null;
        await axios.get(url, config).then((response: any) => {
            if (!response) {
                return;
            }
            data = response;
        });

        return data;
    }

    async post(url: string, params?: any, config?: AxiosRequestConfig) {
        let data: any = null;
        await axios.post(url, params, config).then((response: any) => {
            if (!response) {
                return;
            }
            data = response;
        });

        return data;
    }

    async put(url: string, params?: any, config?: AxiosRequestConfig) {
        let data = null;
        await axios.put(url, params, config).then((response: any) => {
            if (!response) {
                return;
            }
            data = response;
        });

        return data;
    }

    async delete(url: string, config?: AxiosRequestConfig) {
        let data = null;
        await axios.delete(url, config).then((response: any) => {
            if (!response) {
                return;
            }
            data = response;
        });

        return data;
    }

    async upload(url: string, file: File, config?: AxiosRequestConfig) {
        let forms = new FormData()
        if (!config) {
            config = {};
        }

        if (!config.headers) {
            config.headers = {};
        }

        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';

        forms.append('file', file);

        let data = null;
        await axios.post(url, forms, config).then((response: any) => {
            if (!response) {
                return;
            }
            data = response;
        });

        return data;
    }

    async options(url: string, config?: AxiosRequestConfig) {
        let data = null;
        await axios.options(url, config).then((response: any) => {
            if (!response) {
                return;
            }
            data = response;
        });

        return data;
    }

    async patch(url: string, data: any, config?: AxiosRequestConfig) {
        let result = null;
        await axios.patch(url, data, config).then((response: any) => {
            if (!response) {
                return;
            }
            result = response;
        });

        return result;
    }

    async request(config: AxiosRequestConfig) {
        let result = null;
        await axios.request(config).then((response: any) => {
            if (!response) {
                return;
            }
            result = response;
        });

        return result;
    }

    async postSoap(method: string, params?: any, config?: any) {
        let data: any = null;
        let paramsText = '';

        if (params) {
            let keys = Object.keys(params);
            if (keys) {
                for (let i in keys) {
                    if (!keys[i] || params[keys[i]]==undefined) {
                        continue;
                    }

                    paramsText += `<${keys[i]}>${params[keys[i]]}</${keys[i]}>`;
                }
            }
        }
        let postBody = `<?xml version="1.0" encoding="utf-8"?>
            <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                <soap:Body>
                    <${method} xmlns="http://tempuri.org/">
                        ${paramsText}
                    </${method}>
                </soap:Body>
            </soap:Envelope>
        `;

        if (!config) {
            config = {};
        }

        if (!config.headers) {
            config.headers = {};
        }

        config.headers["Content-Type"] = "text/xml; charset=utf-8";
        if(config.loading != false) {
            uni.showLoading({
                title: "加载中..."
            })
        }
        delete config["loading"];
        await axios.post((config.url || config.baseURL), postBody, config).then((response: any) => {
            uni.hideLoading();
            console.log(postBody);
            if (!response) {
                return;
            }
            let fxp = require("fast-xml-parser");
            let xmlAnrJson = fxp.parse(response.data)
            let jsonData = xmlAnrJson['soap:Envelope']['soap:Body'][method+'Response'][method+'Result'];
            data = JSON.parse(jsonData.replace(/"\w[\w\d]*":\s*,/, ""))
            if(data.code && data.code!="200" && data.code!="201") {
                return Promise.reject(data)
            }
        }).catch((reason: any) => {
            uni.hideLoading();
            return Promise.reject(reason);
        });

        return Promise.resolve((data.data || data));
    }
}

export default new HttpUtils()